package com.sec.etech.employeesync.confighandler;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sec.etech.employeesync.entity.OrgEmployeeZSkillLevel;
import com.sec.etech.employeesync.mapper.OrgEmployeeZSkillLevelMapper;
import com.sec.etech.employeesync.util.ConfigTableHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Optional;

@Component
@Slf4j
public class SkillLevelConfigHandler implements ConfigTableHandler<OrgEmployeeZSkillLevel> {

    @Resource
    private OrgEmployeeZSkillLevelMapper skillLevelMapper;

    @Override
    public Long getOrCreateConfigId(String... params) {
        String name = params[0];
        OrgEmployeeZSkillLevel skillLevel = getEntityByName(name);
        if (skillLevel == null) {
            skillLevel = new OrgEmployeeZSkillLevel();
            skillLevel.setCode(generateNextCode());
            skillLevel.setName(name);
            skillLevel.setActive(1);
            insertEntity(skillLevel);
            log.info("新增技能等级配置:name={}", name);
        }
        return skillLevel.getSkillLevelId();
    }

    @Override
    public OrgEmployeeZSkillLevel getEntityByName(String name) {
        return skillLevelMapper.selectOne(Wrappers.<OrgEmployeeZSkillLevel>lambdaQuery()
                .eq(OrgEmployeeZSkillLevel::getName, name));
    }

    @Override
    public String generateNextCode() {
        OrgEmployeeZSkillLevel politics = skillLevelMapper.selectOne(Wrappers.<OrgEmployeeZSkillLevel>lambdaQuery()
                .orderByDesc(OrgEmployeeZSkillLevel::getCode)
                .last("limit 1"));

        String lastCode = Optional.ofNullable(politics)
                .map(OrgEmployeeZSkillLevel::getCode)
                .orElse("0");

        return generateNextCode(lastCode);
    }

    @Override
    public void insertEntity(OrgEmployeeZSkillLevel entity) {
        skillLevelMapper.insert(entity);
    }
}
